<template>
  <el-dialog :title="title" :visible.sync="visible" width="30%" :before-close="handleClose">
    <el-form
      status-icon
      ref="formData"
      :rules="rules"
      :model="formData"
      label-width="80px"
      label-position="right"
      style="width:400px"
    >
      <el-form-item label="标签名称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="分类名称" prop="categoryId">
        <el-select v-model="formData.categoryId" clearable filterable placeholder="状态">
          <el-option :label="item.name" :value="item.id" v-for="item in category" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="SubmitForm('formData')" size="mini">确定</el-button>
        <el-button size="mini" @click="handleClose()">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import label from "@/api/label";

export default {
  props: {
    visible: {
      //弹出框
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ""
    },
    // 下拉分类名称
    category: {
      type: Array,
      default: []
    },
    // 表单数据
    formData: {
      type: Object,
      default: {}
    },
    remoteClose: Function
  },
  data() {
    return {
      rules: {
        name: [{ required: true, message: "请输入标签名称", trigger: "blur" }],
        categoryId: [{ required: true, message: "分类名称", trigger: "change" }]
      }
    };
  },
  methods: {
    SubmitForm(formName) {
      this.$refs[formName].validate(valid => {
        //   console.log(valid)// false或true
        if (valid) {
          // 新增和编辑
          this.submitData(1);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 点击取消点击叉号关闭弹窗
    handleClose(val) {
      console.log(this.formData, "formdata");
      this.$refs["formData"].resetFields();
      this.remoteClose(val);
    },
    // 校验接口提交数据
    async submitData(val) {
      let res = null;
      // 编辑
      if (this.formData.id) {
        res = await label.updata(this.formData);
      } else {
        // 新增
        res = await label.add(this.formData);
      }

      if ((res.code = 20000)) {
        this.$message({
          message: "保存成功",
          type: "success"
        });
        this.handleClose(val);
      } else {
        this.$message({
          message: "很遗憾，保存失败",
          type: "danger"
        });
      }

      //   if (responst.code == 20000) {
      //     this.$message({
      //       message: "保存成功",
      //       type: "success"
      //     });
      //     // 关闭窗口
      //     this.handleClose(val);
      //   } else {
      //     this.$message({
      //       message: "很遗憾，保存失败",
      //       type: "danger"
      //     });
      //   }
    }
  }
};
</script>